package cz.data.common.utils;

import cz.data.common.exception.DataException;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class LocalDateUtil {
    private static final String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM",
            "yyyyMMdd", "yyyyMMddHHmm", "yyyyMMddHHmmss",
            "yyyy年MM月dd", "yyyy年MM月dd天"};
    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static String YYYYMMDDHHMM = "yyyyMMddHHmm";
    public static String ISO8601 = "yyyy-MM-dd'T'HH:mm:ss";
    public static String ISO8601X = "yyyy-MM-dd'T'HH:mm:ssX";

    public static final Date parseAll(String date) {
        if (StringUtils.isBlank(date))
            return null;
        try {
            return org.apache.commons.lang3.time.DateUtils.parseDate(date, parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    public static final DateTimeFormatter DATE_TIME_DEFAULT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static LocalDateTime parse(String str) {
        return parse(str, true);
    }

    public static LocalDateTime parse(String str, boolean throwException) {
        try {
            return LocalDateTime.parse(str, DATE_TIME_DEFAULT);
        } catch (Exception ignored) {
            if (throwException) {
                throw new DataException("日期时间格式不正确");
            } else {
                return null;
            }
        }
    }

}
